const express = require('express');
const crypto = require('crypto');
const uuidv4 = require('uuid').v4;

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

// ============================
// 1. 参数准备 
// ============================
const algorithm = 'aes-256-cbc';    // aes-128-cbc / aes-192-cbc 也可 
const iv = crypto.randomBytes(16);    // CBC IV 固定 16B 
const key = Buffer.from("zj2F9#aU3$vE5nX3@qR7tY4wF2*hA1cR", 'utf8'); // 32B = 256bit；16B=128bit 

const hmacAlgorithm = 'sha256';    // HMAC算法
const hmacKey = 'Kj8#mN5$pL9&vX3@qR4tY7wZ2*hC6bM1';    // HMAC密钥应独立于AES密钥 

// ============================
// 2. 加密函数 
// ============================
function encrypt(plainText) {
  console.log('IV for this encryption:', iv.toString('base64'));
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(plainText, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return {
    encrypted,
    iv: iv.toString('base64')    // IV 也要发给对方 
  };
}

function encryptWithMetadata(plainText) {
  const nonce = uuidv4().replace(/-/g, '').slice(-32).toLowerCase(); // 随机数
  const timestamp = Math.floor(Date.now());
  const { encrypted, iv } = encrypt(plainText);

  // const signInput = `encrypted=${encrypted}&iv=${encodeURIComponent(iv)}&nonce=${nonce}&timestamp=${timestamp}`;
  const signInput = new URLSearchParams({
    encrypted,
    iv,
    nonce,
    timestamp
  }).toString();
  const sign = crypto.createHmac(hmacAlgorithm, hmacKey).update(signInput).digest('hex');

  return {
    encrypted,
    iv,
    nonce,
    timestamp,
    sign
  };
}

app.post('/api/activate', (req, res) => {
  // const { cdk, version, timestamp, sign, device_code, author_id } = req.body;
  // const encryptedData = encryptWithMetadata(JSON.stringify({ activatedAt: new Date().toISOString() }));
  const encryptedData = encryptWithMetadata(JSON.stringify({ activatedAt: '2026-10-12T07:00:02.178Z', cdk: 'cdk-cdk-cdk-cdk', expiresAt: '2026-10-12T07:00:02.178Z' }));
  res.status(200).json({
    status: 'success',
    data: encryptedData
  });
});

app.post('/api/get_code', (req, res) => {
  // const encryptedData = encryptWithMetadata(JSON.stringify({ file_hashes: [], files: [] }));
  res.status(200).json({
    code: 200,
    //data: encryptedData
    data: {
      file_hashes: [],
      files: []
    }
  });
});

app.post('/api/get_points', (req, res) => {
  const encryptedData = encryptWithMetadata(JSON.stringify({ points: 1000 }));
  res.status(200).json({
    status: 'success',
    data: encryptedData
  });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});